#! /usr/bin/python
# -*- coding: utf-8 -*-

from google.appengine.ext import db

def increment_counter(key, amount):
    obj = db.get(key)
    obj.counter += amount
    obj.put()
    return obj.counter

class Accumulator(db.Model):
    counter = db.IntegerProperty()
    type = db.StringProperty(multiline=False)

class AtomicCounter:
    def __init__(self, counterType):
        self.counterType = counterType
        self.gql = db.GqlQuery("SELECT * FROM Accumulator WHERE type = :type", type=self.counterType)
        self.acc = self.gql.get()
    
    def init(self, initValue):
        if not self.acc:
            self.acc = Accumulator()
        self.acc.counter = initValue
        self.acc.type = self.counterType
        self.acc.put()
        
    def getCounter(self):
        self.acc = self.gql.get()
        if self.acc:
            return self.acc.counter
        else:
            return None
    
    def AtomicInc(self):
        return db.run_in_transaction(increment_counter, self.acc.key(), 1)